package com.qing.expert.modules.expert.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qing.expert.common.exception.BusinessException;
import com.qing.expert.modules.expert.entity.ExpertApply;
import com.qing.expert.modules.expert.mapper.ExpertApplyMapper;
import com.qing.expert.modules.expert.service.ExpertApplyService;
import com.qing.expert.modules.expert.vo.request.ExpertApplyRequest;
import com.qing.expert.modules.expert.vo.response.ExpertApplyStatusVO;
import com.qing.expert.modules.user.entity.User;
import com.qing.expert.modules.user.mapper.UserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
public class ExpertApplyServiceImpl implements ExpertApplyService {

    @Resource
    private ExpertApplyMapper expertApplyMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitApply(String userId, ExpertApplyRequest request) {
        // 1. 检查用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 2. 检查是否已经是达人
        if (user.getRole() == 2) {
            throw new BusinessException("您已经是达人了");
        }

        // 3. 检查是否有正在审核的申请
        Long count = expertApplyMapper.selectCount(
                new LambdaQueryWrapper<ExpertApply>()
                        .eq(ExpertApply::getUserId, userId)
                        .eq(ExpertApply::getStatus, 0));
        if (count > 0) {
            throw new BusinessException("您已提交申请，请等待审核");
        }

        // 4. 创建申请记录
        ExpertApply apply = new ExpertApply()
                .setApplyId(IdUtil.getSnowflakeNextIdStr())
                .setUserId(userId)
                .setCategoryId(request.getCategoryId())
                .setDescription(request.getDescription())
                .setCertificateImages(request.getCertificateImages())
                .setPriceMin(request.getPriceMin())
                .setPriceMax(request.getPriceMax())
                .setStatus(0)
                .setCreateTime(LocalDateTime.now());

        expertApplyMapper.insert(apply);
        log.info("用户[{}]提交达人申请[{}]", userId, apply.getApplyId());
    }

    @Override
    public ExpertApplyStatusVO getApplyStatus(String userId) {
        // 查询最近一条申请记录的状态
        Integer status = expertApplyMapper.getLatestApplyStatus(userId);

        ExpertApplyStatusVO vo = new ExpertApplyStatusVO();

        if (status == null) {
            return vo.setStatus(0); // 未申请
        }

        // 如果已通过，查询用户是否已经是达人
        if (status == 1) {
            User user = userMapper.selectById(userId);
            if (user != null && user.getRole() == 2) {
                return vo.setStatus(2); // 已通过
            }
            return vo.setStatus(1); // 通过但还未更新角色
        }

        // 如果是待审核状态(0)，直接返回0
        if (status == 0) {
            return vo.setStatus(0); // 待审核
        }

        return vo.setStatus(3); // 已拒绝(status == 2)
    }
}